<template>
  <div>
    <!-- 用户管理 -->
    <el-card>
      <!-- 搜索框 -->
      <el-form inline>
        <el-form-item>
          <el-input
            v-model="userInfo.username"
            placeholder="用户名"
            type="text"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchUserName"
            >查询</el-button
          >
          <el-button @click="clearSearch">清空</el-button>
        </el-form-item>
      </el-form>
      <!-- 添加/批量删除按钮 -->
      <div style="margin: 0 0 20px 0">
        <el-button type="primary" @click="addOrEditUser()">添加</el-button>
        <el-button type="danger" @click="deleteAllSelection"
          >批量删除</el-button
        >
      </div>

      <!-- 表格 -->
      <el-table
        border
        stripe
        :data="userManageListByPage"
        @selection-change="SelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" width="55" type="index"></el-table-column>
        <el-table-column
          label="用户名"
          width="150"
          prop="username"
        ></el-table-column>
        <el-table-column
          label="用户昵称"
          width="150"
          prop="nickName"
        ></el-table-column>
        <el-table-column label="角色列表" prop="roleName"></el-table-column>
        <el-table-column label="创建时间" prop="gmtCreate"></el-table-column>
        <el-table-column label="更新时间" prop="gmtModified"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <!-- 设置按钮 -->
            <el-button
              type="info"
              size="mini"
              icon="el-icon-user"
              title="设置角色"
              @click="userSetting(row)"
            ></el-button>
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="addOrEditUser(row)"
              title="修改用户"
            ></el-button>
            <!-- 删除按钮 -->
            <!-- 此处气泡确认框 用@confirm触发不了事件 只能用@onConfirm 为了保险 两个都写上 -->
            <el-popconfirm
              :title="`确认删除${row.username}吗?`"
              @confirm="deleteSingleUser(row)"
              @onConfirm="deleteSingleUser(row)"
              style="margin: 0 0 0 10px"
            >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                slot="reference"
                title="删除用户"
              ></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[5, 10, 15]"
        @current-change="currentPageChange"
        @size-change="pageSizeChange"
        layout="prev,pager,sizes,total,->,jumper"
      ></el-pagination>
    </el-card>

    <!-- 添加/修改用户 dialog -->
    <el-dialog
      :title="addOrEditDialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="addOrEditUserInfo.username" type="text"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="addOrEditUserInfo.nickName" type="text"></el-input>
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input
            v-model="addOrEditUserInfo.password"
            type="password"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureToAddOrEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 设置角色 dialog -->
    <el-dialog title="设置角色" :visible.sync="settingUserDialogVisiable">
      <el-form label-width="100px">
        <el-form-item label="用户名">
          <el-input disabled :value="settingUserInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox
            label="全选"
            :indeterminate="isIndeterminate"
            v-model="checkAll"
            @change="CheckAllChange"
          ></el-checkbox>
          <div style="margin: 15px 0"></div>
          <el-checkbox-group v-model="roleVo.roleIdList" @change="checkboxChange">
            <el-checkbox
              v-for="role in allRolesList"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="saveUserRole">保存</el-button>
        <el-button @click="settingUserDialogVisiable = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqUserManageListByPage,
  reqAddOrEditUser,
  reqDeleteAllSelection,
  reqDeleteSingleUser,
  reqUserRoleInfo,
  reqUserDoAssign,
} from "@/api/user";
import { Message } from "element-ui";
export default {
  name: "User",
  data() {
    return {
      //数据1:获取到的管理用户分页列表
      userManageListByPage: [],
      //数据2:管理用户分页列表 总条数
      total: 0,
      //数据3:当前页
      currentPage: 1,
      //数据4:每页条数
      pageSize: 5,
      //数据5:用户信息
      userInfo: {
        username: "",
        password: "",
        nickName: "",
      },
      //数据6:添加/修改dialog标题
      addOrEditDialogTitle: "",
      //数据7:控制添加/修改dialog显示隐藏
      dialogVisible: false,
      //数据8:添加/修改用户 表单信息
      addOrEditUserInfo: {
        username: "",
        nickName: "",
        password: "",
        id: "",
      },
      //数据9:table表格中选中的所有用户 组成的id列表
      selectionAllUserIdList: [],
      //数据10:控制批量删除dialog显示隐藏
      settingUserDialogVisiable: false,
      //数据11:设置用户的信息
      settingUserInfo: {
        username: "",
      },
      //数据12：所有角色名 组成的字符串列表
      allRolesList: [],
      //数据13：所有选中的角色 id
      // selectRolesList: [],
      //数据14：设置角色 全选  indeterminate 状态，只负责样式控制
      isIndeterminate: false,
      //数据15：全选绑定值
      checkAll: false,
      //数据16:设置用户角色保存的信息
      roleVo:{
        roleIdList:[],
        userId:0
      },
    };
  },
  methods: {
    //方法1:获取管理用户分页列表
    async getUserManageListByPage(data) {
      try {
        //data存在 则是搜索/清空逻辑
        if (data) {
          const result = await reqUserManageListByPage(1, 5, data);
          this.userManageListByPage = result.data.items;
          this.total = result.data.total;
          console.log("搜索", result);
        } else {
          //初始逻辑
          const result = await reqUserManageListByPage(
            this.currentPage,
            this.pageSize
          );
          this.userManageListByPage = result.data.items;
          this.total = result.data.total;
          console.log("初始", result);
        }
      } catch (e) {
        Message.error("请求管理用户分页列表失败");
      }
    },
    //方法2:当前页改变事件
    currentPageChange(v) {
      console.log("v", v);

      this.currentPage = v;
      this.getUserManageListByPage();
    },
    //方法3:每页条数改变事件
    pageSizeChange(v) {
      this.pageSize = v;
      this.getUserManageListByPage();
    },
    //方法4:查询用户名事件
    searchUserName() {
      try {
        this.getUserManageListByPage(this.userInfo.username);
      } catch (e) {}
    },
    //方法5:查询清空事件
    clearSearch() {
      this.userInfo.username = "";
      this.currentPage = 1
      this.getUserManageListByPage(this.userInfo.username);
    },
    // 方法6:添加/编辑按钮点击事件
    addOrEditUser(row) {
      //有row则为修改逻辑
      console.log("row", row);
      if (row) {
        //修改逻辑
        this.addOrEditDialogTitle = "修改用户";
        //用这一行的数据填充表单
        this.addOrEditUserInfo = {
          username: row.username,
          nickName: row.nickName,
          password: row.password,
          id: row.id,
        };
        this.dialogVisible = true;
      } else {
        //添加逻辑
        this.addOrEditDialogTitle = "添加用户";
        //清空上一次添加的遗留数据
        this.addOrEditUserInfo = {
          username: "",
          nickName: "",
          password: "",
          id: "",
        };
        this.dialogVisible = true;
      }
    },
    //方法7:dialog添加或修改用户 确定事件
    async sureToAddOrEdit() {
      if (this.addOrEditDialogTitle === "添加用户") {
        try {
          //发送添加请求
          await reqAddOrEditUser(this.addOrEditUserInfo);
          //关闭dialog
          this.dialogVisible = false;
          //重新请求数据
          this.getUserManageListByPage();
          Message.success("添加成功");
        } catch (e) {
          Message.error("添加失败");
        }
      } else {
        //修改逻辑
        try {
          //发送修改请求
          await reqAddOrEditUser(this.addOrEditUserInfo);
          //关闭dialog
          this.dialogVisible = false;
          //刷新页面
          this.getUserManageListByPage();
          Message.success("修改成功");
        } catch (e) {
          Message.error("修改失败");
        }
      }
    },
    //方法8:table表格选中 事件
    SelectionChange(selection) {
      console.log("selection", selection);
      //提取所有的项里的id组成列表
      this.selectionAllUserIdList = selection.map((item) => {
        return item.id;
      });
    },
    //方法9:批量删除按钮 点击事件
    deleteAllSelection() {
      this.$confirm("确定删除吗?", "", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            await reqDeleteAllSelection(this.selectionAllUserIdList);
            this.getUserManageListByPage();
            Message.success("批量删除成功");
          } catch (error) {
            Message.error("批量删除失败");
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //方法10:单个 删除品牌按钮 点击事件
    async deleteSingleUser(row) {
      console.log("触发了");
      try {
        await reqDeleteSingleUser(row.id);
        this.getUserManageListByPage();
        Message.success("删除成功");
      } catch (e) {
        Message.error("删除失败");
      }
    },
    //方法11:设置用户按钮 点击事件
    async userSetting(row) {
      console.log("row", row);
      this.settingUserInfo.username = row.username;
      this.roleVo.userId = row.id
      try {
        const result = await reqUserRoleInfo(row.id);
        console.log("方法11", result);
        this.allRolesList = result.data.allRolesList;
        //清空上一次的默认选中的数据
        this.roleVo.roleIdList = [];
        this.roleVo.roleIdList = result.data.assignRoles.map((item) => item.id);
        // console.log('allRolesList',this.allRolesList);
        // console.log('roleVo.roleIdList',this.roleVo.roleIdList);
      } catch (error) {}
      this.settingUserDialogVisiable = true;
    },
    //方法12：checkboxgroup改变事件 参数是所有选中项组成的字符串数组
    checkboxChange(value) {
      console.log("value", value);
      this.roleVo.roleIdList = value;
      //当选中角色列表的长度 等于 所有角色列表的长度 全选设置为勾选状态
      if(this.roleVo.roleIdList.length===this.allRolesList.length){
        this.checkAll = true
      }else{
        this.checkAll = false
      }
    },
    //方法13:全选改变事件
    CheckAllChange(value) {
      // console.log("value", value);
      //判断是全选 还是取消全选
      if (value) {
        //全选 
        this.roleVo.roleIdList = this.allRolesList.map((item) => {
          return item.id;
        });
      } else {
        //取消全选
        this.roleVo.roleIdList = []
      }
    },
    //方法14:设置角色dialog 保存按钮 点击事件
    async saveUserRole(){
      try {
        await reqUserDoAssign(this.roleVo);
        this.settingUserDialogVisiable = false
        this.getUserManageListByPage()
        Message.success("设置角色成功")
      } catch (error) {
        Message.error("设置角色失败")
      }
    },
  },
  mounted() {
    //初始化1:请求管理用户分页列表
    this.getUserManageListByPage();
  },
};
</script>

<style></style>
